/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CommandLineBuilder {
    private List<String> args;

    public CommandLineBuilder(String bin) {
        this.args = new ArrayList();
        this.args.add(quote(bin));
    }

    public CommandLineBuilder addArg(String arg) {
        return addArgs(arg);
    }

    public CommandLineBuilder addArgs(String... args) {
        for (String arg : args) {
            if (null != arg) {
                this.args.add(quote(arg));
            }
        }

        return this;
    }

    public CommandLineBuilder addArgs(Iterable<String> args) {
        for (String arg : args) {
            arg = null != arg ? arg: "";
            this.args.add(quote(arg));
        }
        return this;
    }

    public CommandLineBuilder addEqualsArg(String name, String value) {
        if (null != value && 0 < value.length()) {
            this.args.add(quote(new StringBuilder().append(name).append("=").append(value).toString()));
        } else {
            this.args.add(quote(name));
        }

        return this;
    }

    public CommandLineBuilder addRawArgs(String... args) {
        for (String arg : args) {
            if (null != arg) {
                this.args.add(arg);
            }
        }

        return this;
    }

    public CommandLineBuilder addRawArgs(Iterable<String> args) {
        for (String arg : args) {
            arg = null != arg ? arg : "";
            this.args.add(arg);
        }
        return this;
    }

    public List<String> getArgs() {
        return this.args;
    }

    public String[] getArgsAsArray() {
        return args.toArray(new String[args.size()]);
    }

    public static String quote(String arg) {
        boolean needsQuoting = (arg.indexOf(32) >= 0) || (arg.indexOf(34) >= 0);
        if (!needsQuoting) {
            return arg;
        }
        StringBuilder buf = new StringBuilder();

        boolean escaped = false;
        for (char c : arg.toCharArray()) {
            if ((!escaped) && ((c == '"') || (c == ' '))) {
                buf.append("\\");
            }
            escaped = c == '\\';
            buf.append(c);
        }

        return buf.toString();
    }

    public String toString() {
        StringBuilder buf = new StringBuilder();

        boolean delim = false;
        for (String arg : this.args) {
            if (delim) {
                buf.append(' ');
            }
            buf.append(quote(arg));
            delim = true;
        }

        return buf.toString();
    }

    public static void main(String[] args) {
        CommandLineBuilder builder = new CommandLineBuilder("catalina.bat");
        builder.addArg("run");

        ProcessBuilder b = new ProcessBuilder(builder.getArgs());
        Map<String, String> env = b.environment();
        env.put("PATH", env.get("PATH") + File.pathSeparator + "E:\\Applications\\apache-tomcat-7.0.54");
        env.put("CATALINA_HOME", "E:\\Applications\\apache-tomcat-7.0.54");

        try {
            Process proc = b.start();
            InputStream is = proc.getInputStream();

            Charset charset = Charset.forName(System.getProperty("sun.jnu.encoding", "file.encoding"));
            String text = IOUtils.readText(is, charset, false);
            System.err.println(text);

            text = IOUtils.readText(proc.getErrorStream(), charset, false);
            System.out.println(text);

            int i = proc.waitFor();
            System.out.println(i);
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
            System.err.println(Throwables.getStackTraceAsString(ioe));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.exit(0);
    }
}